import moment from 'moment'

export const parseQuery = (str : string) => {
    if (str.indexOf('?') == -1) {
        return {}
    }
    const urls = str.split('?')
    const querys = {}
    urls[1].split('&').forEach((item) => {
        const tmp = item.split('=')
        querys[tmp[0]] = tmp[1]
    })
    return querys
}

export const timeFormatter = (timestamp : number, formatter='yyyy/MM/DD') => {
    if (timestamp <= 0) {
        return ''
    }
    return moment(timestamp * 1000).format(formatter)
}

export const showFormatter = (values : any[], value : any) => {
    const fitlers = values.filter(item => item[0] == value)
    return fitlers.length > 0 ? fitlers.pop()[1] : ''
}

export const range = (start: number, end: number) => Array(end - start + 1).fill().map((_, idx: number) => start + idx)

export const setItem = (key : string, value : any, type='json') => {
    if (type != 'string') {
        localStorage.setItem(key, JSON.stringify(value))
    } else {
        localStorage.setItem(key, value)
    }
}

export const getItem = (key : string, type='json') => {
    if (type != 'string') {
        const val = localStorage.getItem(key)
        if (val) {
            return JSON.parse(val)
        }
        return ''
    }
    return localStorage.getItem(key)

}

export default {
    parseQuery,
    timeFormatter,
    showFormatter,
    setItem,
    getItem,
}